Storytelling with ggplot2:
Using custom functions to sequence visualizations
McCall Pitcher
Data Visualization Specialist
Center for Data and Visualization Sciences
Duke University Libraries
mutate(
positive = case_when(
metric == "CAR" & rate > 0 ~"a",
metric == "Retention Rate" & rate > 0 ~"b",
metric == "Graduation Rate" & rate > 0 ~"c",
T ~ "d"),
negative = case_when(
metric == "CAR" & rate < 0 ~"a",
metric == "Retention Rate" & rate < 0 ~"b",
metric == "Graduation Rate" & rate < 0 ~"c",
T ~ "d"),
goal = case_when(
metric == "CAR" & rate > 1 ~"a",
metric == "Retention Rate" & rate > 1 ~"b",
metric == "Graduation Rate" & rate > 1 ~"c",
T ~ "d"),
case = case_when(
metric == "CAR" & college %in% c("GGG","MMM","FFF")~"a",
metric == "Retention Rate" & college %in% c("GGG","MMM","FFF")~"b",
metric == "Graduation Rate"& college %in% c("GGG","MMM","FFF")~"c",
T~"d")
)build_chart <- function(
fill_var,
color_var,
annotation_color
) {
ggplot(dat, aes(x = rate, y = college) +
geom_col(aes(fill = {{ fill_var }})) +
geom_text(dat |> filter(rate < 0),
mapping = aes(x = .1, y = college, label = college,
color = {{ color_var }})) +
geom_text(dat |> filter(rate > 0),
mapping = aes(x = -.1, y = college, label = college,
color = {{ color_var }})) +
geom_segment(brackets,
mapping = aes(x = x, xend = xend, y = y, yend = yend),
color = annotation_color) +
facet_wrap(~metric, scales = 'free_y') +
scale_fill_manual(values = c("#949e48", "#ea9f2c",
"#0290c0", "grey90")) +
scale_color_manual(values = c("grey40","grey90"))
}Thank you!
mccall.pitcher@duke.edu
McCall Pitcher
Data Visualization Specialist
Center for Data and Visualization Sciences
Duke University Libraries